package com.ebt.m.users;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.ebt.m.AppContext;
import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.activity.BaseToolBarActivity;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.commons.utils.RxUtil;
import com.ebt.m.commons.utils.ToastUtil;
import com.ebt.m.data.bean.UserInfo;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.proposal_v2.widget.dialog.EBTProgressDialog;
import com.ebt.m.users.bean.CardData;
import com.ebt.m.utils.ConfigData;
import com.ebt.m.utils.EbtUtils;
import com.ebt.m.utils.InputCheckUtil;
import com.ebt.m.utils.PhotoCaptureUtil;
import com.ebt.m.view.CircleImageView;
import com.ebt.m.widget.MDEBTDialog;

import org.json.JSONObject;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by wanglu on 2018/2/7.
 */

public class CardEditActivity extends BaseToolBarActivity {
    @BindView(R.id.card_avatar)
    CircleImageView cardAvatar;
    @BindView(R.id.iv_arrow)
    ImageView ivArrow;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.card_name)
    EditText cardName;
    @BindView(R.id.card_company)
    TextView cardCompany;
    @BindView(R.id.tv_performance)
    TextView tvPerformance;
    @BindView(R.id.card_performance)
    EditText cardPerformance;
    @BindView(R.id.card_phone)
    EditText cardPhone;
    @BindView(R.id.introduction_container)
    RelativeLayout introductionContainer;
    @BindView(R.id.honour_container)
    RelativeLayout honourContainer;
    @BindView(R.id.services_container)
    RelativeLayout servicesContainer;

    CardData cardData;
    @BindView(R.id.avatar_container)
    RelativeLayout avatarContainer;
    private String newPortraitPath = "";
    private EBTProgressDialog mProgressDialog;
    public static final int REQUEST_INTRODUCTION = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_carddata_edit);
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_TITLE);
        setTitle("编辑名片");
        ButterKnife.bind(this);
        cardData = (CardData) getIntent().getSerializableExtra("carddata");
        if (cardData == null) {
            ToastUtil.show(this, "名片信息为空");
            finish();
        } else {
            initView();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_card_edit, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        saveCardData();
        return super.onOptionsItemSelected(item);
    }

    private void saveCardData() {
        String newName = cardName.getText().toString().trim();
        String newPost = cardPerformance.getText().toString().trim();
        String newPhone = cardPhone.getText().toString().trim();
        if (TextUtils.isEmpty(newName) || TextUtils.isEmpty(newPhone) || TextUtils.isEmpty(newPost)) {
            ToastUtil.show(this, "选项不得为空");
            return;
        } else if (!TextUtils.isEmpty(newPortraitPath) || !newPhone.equals(cardData.getPhone()) || !newName.equals(cardData.getUserName()) || !newPost.equals(cardData.getPost()) || !newPhone.equals(cardData.getPhone())) {
            if (InputCheckUtil.phoneCheck(newPhone)) {
                mProgressDialog.show();
                EBTAPI ebtapi = AppInitService.getEbtApi();
                Observable.just(newPortraitPath)
                        .flatMap(path -> {
                            if (TextUtils.isEmpty(path)) {
                                return Observable.just("");
                            } else {
                                MultipartBody.Part file = generateMultipartBody("file", newPortraitPath);
                                UserInfo userInfo = AppContext.getCurrentUser();
                                String agentId = userInfo.getUserId() + "/";
                                return ebtapi.updateFile(file, "", ConfigData.CARD_PORTRAIT_BUCKET, ConfigData.CARD_PORTRAIT_DISK_PATH + agentId)
                                        .map(resultFile -> {
                                            if (resultFile != null && resultFile.data != null && !TextUtils.isEmpty(resultFile.data.getDownLoadUrl())) {
                                                return resultFile.data.getDownLoadUrl();
                                            } else {
                                                return "";
                                            }
                                        });
                            }
                        })
                        .flatMap(newPortraitPath -> {
                            CardData tempCardData = new CardData();
                            tempCardData.setPortraitAddress(TextUtils.isEmpty(newPortraitPath) ? cardData.getPortraitAddress() : newPortraitPath);
                            tempCardData.setUserName(newName);
                            tempCardData.setPost(newPost);
                            tempCardData.setPhone(newPhone);
                            return ebtapi.modifyCardData(tempCardData)
                                    .map(result -> {
                                        try {
                                            JSONObject jsonObject = new JSONObject(result.body().string());
                                            long num = jsonObject.getJSONObject("data").getLong("num");
                                            return num;
                                        } catch (Exception e) {
                                            return Long.valueOf(0);
                                        }
                                    });
                        })
                        .compose(RxUtil.rxTransformer(this))
                        .subscribe(num -> {
                            mProgressDialog.dismiss();
                            if (num == 0) {
                                ToastUtil.show(this, "保存名片失败");
                            } else {
                                ToastUtil.show(this, "保存名片成功");
                                finish();
                            }
                        }, throwable -> {
                            mProgressDialog.dismiss();
                            NetUtils.checkHttpException(this, throwable);
                            throwable.printStackTrace();
                        });
            } else {
                ToastUtil.show(this, "手机号格式不正确");
                return;
            }
        } else {
            finish();
            return;
        }
    }

    private boolean checkInput(String newName, String newPost, String newPhone) {
        if (TextUtils.isEmpty(newName) || TextUtils.isEmpty(newPhone) || TextUtils.isEmpty(newPost)) {
            ToastUtil.show(this, "选项不得为空");
            return false;
        } else if (!TextUtils.isEmpty(newPortraitPath) || !newName.equals(cardData.getUserName()) || !newPost.equals(cardData.getPost()) || !newPhone.equals(cardData.getPhone())) {
            if (!newPhone.equals(cardData.getPhone())) {
                if (InputCheckUtil.phoneCheck(newPhone)) {
                    return true;
                } else {
                    ToastUtil.show(this, "手机号格式不正确");
                    return false;
                }
            }
            return true;
        } else {
            return false;
        }
    }

    public MultipartBody.Part generateMultipartBody(String name, String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return null;
        }
        File uploadFile = new File(filePath);
        if (!uploadFile.exists()) {
            return null;
        }
        RequestBody requestFileBody = RequestBody.create(MediaType.parse("multipart/form-data"), new File(filePath));
        return MultipartBody.Part.createFormData(name, uploadFile.getName(), requestFileBody);
    }

    private void initView() {
        Glide.with(this)
                .load(cardData.getPortraitAddress())
                .error(R.drawable.empty_photo)
                .dontAnimate()
                .into(cardAvatar);
        cardName.setText(cardData.getUserName());
        cardCompany.setText(cardData.getCompanyName());
        cardPerformance.setText(cardData.getPost());
        cardPhone.setText(cardData.getPhone());
        initProgressDialog();
    }

    @OnClick({R.id.introduction_container, R.id.honour_container, R.id.services_container, R.id.avatar_container})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.introduction_container:
                Intent intent = new Intent(this, CardIntroductionActivity.class);
                intent.putExtra("introduction", cardData.getIntroduction());
                startActivityForResult(intent, REQUEST_INTRODUCTION);
                break;
            case R.id.honour_container:
                Intent intent1 = new Intent(this, CardHonourActivity.class);
                startActivity(intent1);
                break;
            case R.id.services_container:
                Intent intent2 = new Intent(this, CardServiceActivity.class);
                startActivity(intent2);
                break;
            case R.id.avatar_container:
                toSelectPhoto();
                break;
        }
    }

    /**
     * 选择照片
     */
    private PhotoCaptureUtil mPhotoCaptureUtil;

    private void toSelectPhoto() {
        String tmpPath = EbtUtils.getCompletePortraitPath();//指定存放路径
        mPhotoCaptureUtil = new PhotoCaptureUtil(this);
        mPhotoCaptureUtil.setFrom(true);
        mPhotoCaptureUtil.setOnPhotoCaptureListener(new PhotoCaptureUtil.OnPhotoCaptureListener() {
            @Override
            public void onPhotoCaptured(final String path) {
                if (TextUtils.isEmpty(path)) {
                    return;
                }

                Glide.with(CardEditActivity.this)
                        .load(new File(path))
                        .error(R.drawable.empty_photo)
                        .dontAnimate()
                        .skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .into(cardAvatar);
                newPortraitPath = path;
            }
        });
        String[] messages = new String[]{"相册", "拍照"};
        new MDEBTDialog.Builder(this)
                .setMessages(messages)
                .setTitle("更改头像")
                .setNegativeButton(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    }
                })
                .setPositiveButton(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    }
                })
                .setOnItemClickListener(new MDEBTDialog.OnItemClickListener() {
                    @Override
                    public void onItemClicked(int index) {
                        if (index == 0) {
                            mPhotoCaptureUtil.startActivity(PhotoCaptureUtil.FROM_ALBUM,
                                    ConfigData.PORTRAIT_WIDTH, ConfigData.PORTRAIT_HEIGHT, tmpPath);
                        } else if (index == 1) {
                            mPhotoCaptureUtil.startActivity(PhotoCaptureUtil.FROM_CAMERA,
                                    ConfigData.PORTRAIT_WIDTH, ConfigData.PORTRAIT_HEIGHT, tmpPath);
                        }
                    }
                })
                .setShowPositiveButton(false)
                .create()
                .show();
    }

    private void initProgressDialog() {
        mProgressDialog = new EBTProgressDialog(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_INTRODUCTION) {
            if (data != null && data.hasExtra("introduction")) {
                String introduction = data.getStringExtra("introduction");
                cardData.setIntroduction(introduction);
            }
        }
    }
}
